
require 'date'
require 'net/http'

require 'json'

module Raklur
	class Search
		attr_accessor :update_interval, :title, :url
		attr_reader :account

		def initialize account, title=nil, url=nil
			@account = account
			@title = title
			@url = url
			@delay = nil
			@update_interval = 60 * 3 # in seconds
			@latest_update =  nil  # FIXME: load from database or 0
			@latest_id = 0 # FIXME: load from database or 0
			yield self if block_given?
		end

		def update?
			return true if @latest_update.nil?

			if next_update < Time.now then 
				return true
			else 
				return false
			end
		end

		def next_update
			latest = if @latest_update.nil? then Time.now
					 else @latest_update
					 end
			( latest + @update_interval )
		end

		def update!
			puts "Updating from #{@url}.js"
			url = "%s.json" % @url 
			response = nil
			res = Net::HTTP.start( @account.server, @account.port) do |http|
				puts "requesting #{@account.server}#{url}"

				req = Net::HTTP::Get.new( url )
				req.basic_auth @account.username, @account.password
				response = http.request( req ) 
			end
			if not response.kind_of? Net::HTTPSuccess
				raise RuntimeError, response.inspect
			end

			# FIXME: add into database
			#print response.body
			js = JSON.parse response.body
			puts JSON.pretty_generate( js )

			puts js
			@latest_update = Time.now 
			@latest_id += 1
		end

		def to_s
			return "%s : %s (next in %s)" % [ @account.title, @title, (next_update - Time.now) .to_i ]
		end
	end
end

